<template>
  <div class="producsBox" v-if="data">
    <div class=" list-b-12">

      <div class="producsBox-head">
        <div class="producsBox-img">
          <ElImgBox :data="data.productColorDraftFileList[0] || {}" :urlList="data.productColorDraftFileList"
            urlKey="draftFileUrl" :width="120" />
        </div>
        <div class="producsBox-main list-b-8">
          <h3>{{ data.orderProduct?.productName || '--' }}</h3>
          <FlexBox :list="4" :margin="6">
            <dl>
              <dt>产品编号：</dt>
              <dd>{{ data?.orderProduct?.productNumber || '--' }}</dd>
            </dl>
            <dl>
              <dt>产品类型：</dt>
              <dd>{{ data?.orderProduct?.productTypeName || '--' }}</dd>
            </dl>
            <dl>
              <dt>产品版本：</dt>
              <dd>{{ `V${data?.orderProduct?.updateVersion + 1}` }}</dd>
            </dl>
            <dl>
              <dt>产品尺寸：</dt>
              <dd>{{ data?.orderProduct?.productSize || '--' }}</dd>
            </dl>
            <dl>
              <dt>标签数量：</dt>
              <dd>{{ data?.orderProduct?.productTagNumber || 0 }}{{ data?.orderProduct?.productUnit }}</dd>
            </dl>
            <dl>
              <dt>产品单价：</dt>
              <dd class="list-r-8">
                <span>{{ hasEditPower ? `${productStepPrice(data)}元` : '无权查看' }}</span>
                <s class="text-color-info " v-if="!!data.originalPrice && hasEditPower">{{
                  data.originalPrice }}元</s>
              </dd>
            </dl>
            <dl>
              <dt>产品最低价：</dt>
              <dd>{{ hasEditPower ? `${data?.orderProduct?.minimumAmount || 0}元` : '无权查看' }}</dd>
            </dl>
            <dl class="wAuto">
              <dt>产品要求：</dt>
              <dd>
                <div class="htmlBox" v-html="data?.orderProduct?.productRequirement || '无要求'"></div>
              </dd>
            </dl>
          </FlexBox>
        </div>
      </div>
      <CellBox title="产品规格明细">
        <template #btn v-if="isEdit">
          <el-link type="primary" @click="() => {
            proxy.$exportData(
              {
                thead: [
                  {
                    label: '产品名称',
                    prop: 'productName',
                  },
                  {
                    label: '型号名称',
                    prop: 'modelName',
                  },
                  {
                    label: '生产数量',
                    prop: 'productionQuantity',
                  },
                ],
                tbody: [
                  {
                    productName: data.orderProduct?.productName,
                    modelName: '',
                    productionQuantity: '',
                  }
                ],
                fileName: '型号模板',
              },
            );
          }" icon="Download">下载型号模版</el-link>
          <el-divider direction="vertical" />
          <ElUploadBox accept=".xlsx" @changeBtn="modelUpload">
            <el-link type="primary" icon="Upload">上传型号</el-link>
          </ElUploadBox>
        </template>
        <div class="list-b-8">
          <div class="flex-start-center list-r-6">
            <ElSelectBox :data="data" dataName="orderProductSpecificationListArr" multiple
              :options="data.productSpecificationList" labelName="productSpecificationName"
              valueName="productSpecificationCode" @changeBtn="(value: any, row: any, arr: any) => {
                const _arr = arr.map((el: any) => {
                  const _findRow = data.orderProductSpecificationList.find((find: any) => find.productSpecificationCode === el.productSpecificationCode)
                  return {
                    ...el,
                    productionQuantity: _findRow?.productionQuantity || null,
                    deliveredQuantity: 0,
                    remark: '',
                  }
                })
                data.orderProductSpecificationList = _arr
                productionQuantity(data)
              }" :disabled="!isEdit" />
            <ElInputBox :data="data" dataName="addSpecificationName" placeholder="请输入产品规格名称" :width="320" v-if="isEdit">
              <template #append>
                <el-button @click="
                  addProductSpecification(data, data.addSpecificationName)
                  ">添加规格</el-button>
              </template>
            </ElInputBox>
          </div>
          <TableBoxMx :data="{
            disabled: !isEdit,
            tbody: data.orderProductSpecificationList,
            thead: [
              {
                label: '型号名称',
                prop: 'productSpecificationName',
                align: 'left',
                width: 200,
              },
              {
                label: '生产数量',
                prop: 'productionQuantity',
                align: 'center',
                width: 120,
                formType: 'number',
                formProp: formProp ? `${formProp}.orderProductSpecificationList` : 'orderProductSpecificationList',//必填
                changeBtn: (row: any) => {
                  productionQuantity(data)
                }
              },
              {
                label: '成品库存',
                prop: 'stockQuantity',
                align: 'center',
                width: 120,
              },
              {
                label: '已发货数量',
                prop: 'deliveredQuantity',
                align: 'center',
                width: 160,
              },
              {
                label: '备注',
                prop: 'remark',
                align: 'left',
                width: null,
                formType: 'text',
              },
            ],
          }">
            <template #stockQuantity="{ row }">
              <PopoverTabel title="查看库存" :thead="[
                {
                  label: '库区库位',
                  prop: 'warehouseInfo',
                  align: 'center',
                  width: null,
                },
                {
                  label: '生产批次',
                  prop: 'produceTaskBillNo',
                  align: 'center',
                  width: null,
                },
                {
                  label: '生产日期',
                  prop: 'productionDate',
                  align: 'center',
                  width: null,
                },
                {
                  label: '库存数量',
                  prop: 'stockQuantity',
                  align: 'center',
                  width: null,
                },
              ]" @show='(table: any) => {
                proxy.$api.FinishedProduct
                  .GetFinishedProductStockDetailPageList({
                    pageIndex: 1,
                    pageSize: 999,
                    queryDataBaseFiled: "",
                    likeWords: "",
                    isShowDisabled: 0,
                    productNo: row.productSpecificationCode
                  })
                  .then((res: any) => {
                    table.tbody = res.list.filter((el: any) => el.stockQuantity > 0)
                    table.loading = false
                  })
                  .catch(() => {

                  });
              }' />
            </template>
          </TableBoxMx>
        </div>
      </CellBox>
      <CellBox title="产品基础信息">
        <FlexBox>
          <ElFormItemBox label="客户单号" :prop="formProp ? `${formProp}.customerBillNo` : 'customerBillNo'">
            <ElInputBox :data="data" dataName="customerBillNo" :disabled="!isEdit" />
          </ElFormItemBox>
          <ElFormItemBox label="交货日期" :prop="formProp ? `${formProp}.deliveryDate` : 'deliveryDate'" isRules>
            <ElDayBox :data="data" dataName="deliveryDate" :disabled="!isEdit" />
          </ElFormItemBox>
          <ElFormItemBox label="订单合同" :prop="formProp ? `${formProp}.contractName` : 'contractName'">
            <ElInputBox :data="data" dataName="contractName" disabled />
            <template #btn v-if="isEdit">
              <el-button v-if="data.contractFile" @click="() => {
                proxy.$openUrl(data.contractFile, '_blank');
              }">预览</el-button>
              <ElUploadBox type="all" accept=".pdf,.docx,.doc" @changeBtn="(files: any, dataInfo: any, res: any) => {
                data.contractFile = res.fileUrl;
                data.contractName = res.originalName;
                dataInfo.loading = false
                proxy.$message('上传成功')
              }">
                <el-button>上传</el-button>
              </ElUploadBox>
            </template>
          </ElFormItemBox>
          <ElFormItemBox label="产品版面" :prop="formProp ? `${formProp}.productLayout` : 'productLayout'" isRules>
            <ElSelectBox :data="data" dataName="productLayout" :options="[
              {
                label: '新版',
                value: '新版',
              },
              {
                label: '改版',
                value: '改版',
              },
              {
                label: '老版',
                value: '老版',
              },
            ]" :disabled="!isEdit" />
          </ElFormItemBox>
          <ElFormItemBox label="产品数量" :prop="formProp ? `${formProp}.productQuantity` : 'productQuantity'">
            <ElNumberBox :data="productQuantity(data)" :unit="data.orderProduct?.productUnit" disabled />
          </ElFormItemBox>
          <ElFormItemBox label="计价方式" :prop="formProp ? `${formProp}.paymentMethod` : 'paymentMethod'" isRules>
            <ElSelectBox :data="data" dataName="paymentMethod" :options="proxy.$optionsArr.paymentMethod"
              @changeBtn="setTotalAmountPrice(data)" :disabled="!isEdit" />
          </ElFormItemBox>
          <ElFormItemBox label="产品总额">
            <ElNumberBox :data="totalAmountPrice(data)" unit="元" disabled />
          </ElFormItemBox>
          <ElFormItemBox label="实际金额" :prop="formProp ? `${formProp}.totalAmount` : 'totalAmount'" isRules>
            <ElNumberBox :data="data" dataName="totalAmount" unit="元" :disabled="!isEdit" />
            <template #btn v-if="isEdit">
              <el-tooltip effect="dark" content="更新订单金额" placement="top">
                <el-button @click="() => {
                  data.totalAmount = totalAmountPrice(data)
                }" icon="Refresh"></el-button>
              </el-tooltip>
            </template>
          </ElFormItemBox>
          <ElFormItemBox :label="totalOffers(data) > 0 ? '多收金额' : '优惠金额'">
            <ElNumberBox :data="Math.abs(totalOffers(data))" unit="元" disabled />
          </ElFormItemBox>
          <ElFormItemBox label="数据来源" :prop="formProp ? `${formProp}.dataComeFrom` : 'dataComeFrom'" isRules>
            <ElSelectBox :data="data" dataName="dataComeFrom" :options="[
              {
                label: '无',
                value: 0,
              },
              {
                label: '客户',
                value: 1,
              },
              {
                label: '自编',
                value: 2,
              },
            ]" :disabled="!isEdit" />
          </ElFormItemBox>
          <ElFormItemBox label="数据数量">
            <ElNumberBox :data="data" dataName="dataQuantity" :unit="data.orderProduct?.productUnit"
              :disabled="!isEdit" />
          </ElFormItemBox>
          <ElFormItemBox label="是否生产" :prop="formProp ? `${formProp}.isProductionRequired` : 'isProductionRequired'"
            isRules>
            <ElSelectBox :data="data" dataName="isProductionRequired" :options="[
              {
                label: '不生产',
                value: 0,
              },
              {
                label: '要生产',
                value: 1,
              },
            ]" :disabled="!isEdit" />
          </ElFormItemBox>
          <ElFormItemBox label="业务备注" :prop="`remark`" class="wAuto">
            <ElInputBox :data="data" dataName="remark" type="textarea" :disabled="!isEdit" />
          </ElFormItemBox>
        </FlexBox>
      </CellBox>
      <CellBox title="其他费用">
        <TableBoxMx :data="{
          disabled: !isEdit,
          tbody: data.costList,
          thead: [
            {
              label: '费用类型',
              prop: 'type',
              align: 'left',
              width: 180,
            },
            {
              label: '单价',
              prop: 'price',
              align: 'center',
              width: 180,
            },
            {
              label: '数量',
              prop: 'number',
              align: 'center',
              width: 100,
            },
            {
              label: '总金额',
              prop: 'amount',
              align: 'center',
              width: 100,
            },
            {
              label: '备注',
              prop: 'remarks',
              align: 'left',
              width: null,
            },
          ],
          //操作
          operation: [
            {
              label: '编辑',
              icon: 'Edit',
              click: (row: any) => {
                openPup(row)
              }
            },
            {
              label: '删除',
              icon: 'Delete',
              click: (row: any) => {
                proxy.$api.OrderBusniess
                  .DeleteSaleOrderFeeDetail({
                    code: row.saleOrderFeeDetailCode,//	唯一编码
                  })
                  .then((res: any) => {
                    proxy.$message(`删除成功`);
                    getCostList()
                  })
                  .catch(() => {

                  });
              }
            }
          ],
          add: () => {
            openPup()
          }
        }">
        </TableBoxMx>
      </CellBox>
    </div>
    <ElPupFormBox :pup="pup">
      <template #default="{ form }">
        <ElFormItemBox label="费用类型" prop="type" isRules>
          <ElInputBox :data="form" dataName="type" />
        </ElFormItemBox>
        <ElFormItemBox label="单价" prop="price" isRules>
          <ElNumberBox :data="form" dataName="price" />
        </ElFormItemBox>
        <ElFormItemBox label="数量" prop="number" isRules>
          <ElNumberBox :data="form" dataName="number" />
        </ElFormItemBox>
        <ElFormItemBox label="总金额" prop="amount">
          <ElNumberBox :data="amount(form)" />
        </ElFormItemBox>
        <ElFormItemBox label="备注" prop="remarks">
          <ElInputBox :data="form" dataName="remarks" type="textarea" />
        </ElFormItemBox>
      </template>
    </ElPupFormBox>
  </div>
</template>
<script setup lang="ts">
const { proxy } = getCurrentInstance() as any;
const props = withDefaults(
  defineProps<{
    data?: any;
    index?: number;
    hasEditPower?: boolean;
    formProp?: string;
    isEdit?: boolean;
  }>(),
  {

  },
);
const modelUpload = (files: any, dataInfo: any, res: any) => {
  var formData = new FormData();
  formData.append("productCode", props.data.orderProduct.productCode);
  formData.append("file", files.file);
  proxy.$api.OrderBusniess
    .ImportProductSpecification(formData)
    .then((res: any) => {
      proxy.$message("上传成功");
      dataInfo.loading = false
      res.forEach((el: any) => {
        addProductSpecification(props.data, el.productSpecificationName, el.productionQuantity);
      });
    })
    .catch(() => { });
}
const addProductSpecification = (row: any, name: string, number?: number) => {
  if (!!!name) {
    proxy.$message("请输入规格名称", 'error');
    return;
  }
  //判断规格是否存在
  const _addState = row.productSpecificationList.some((item: any) => item.productSpecificationName === name)
  const _addState1 = row.orderProductSpecificationList.some((item: any) => item.productSpecificationName === name)
  if (_addState1) {
    proxy.$message("已存在请勿重复添加", 'error');
    return;
  }
  //如果产品有规格却没选中
  if (_addState) {
    _getArr()
    return;
  }
  //不存在则新增
  proxy.$api.OrderBusniess.SaveProductSpecification({
    productSpecificationName: name,
    productCode: row.orderProduct.productCode,
    isDisable: 0,
  })
    .then((res: any) => {
      proxy.$api.OrderBusniess.GetSingleProductByProductCode({
        queryBy: 2,
        queryValue: row.orderProduct.productCode,
      })
        .then((res: any) => {
          row.productSpecificationList = res.productSpecificationList
          _getArr()
        })
        .catch(() => {

        });
    })
    .catch(() => {

    });
  function _getArr() {
    const _addRow = row.productSpecificationList.find((item: any) => item.productSpecificationName === name)
    _add(_addRow)
  }
  function _add(addRow: any) {
    row.orderProductSpecificationList.push({
      ...addRow,
      productionQuantity: number || null,
      deliveredQuantity: 0,
      remark: '',
    })
    row.orderProductSpecificationListArr.push(addRow.productSpecificationCode)
  }
}
const pup = reactive({
  state: false,
  typeName: 1,
  title: `其他费用`,
  width: 600,
  height: 'auto',
  form: {
    type: "", // 费用类型
    remarks: "", // 备注
    price: null, // 单价
    number: null, // 数量
    amount: null // 总金额
  },
  btns: [
    {
      title: '保存',
      type: 'primary',
      click: (pup: any, resetForm: Function) => {
        const form = pup.form
        const _form = {
          saleOrderCode: props.data.saleOrderCode, // 订单编码
          saleOrderFeeDetailCode: form.saleOrderFeeDetailCode, // 费用唯一编码
          type: form.type, // 费用类型
          remarks: form.remarks, // 备注
          price: form.price, // 单价
          number: form.number, // 数量
          amount: form.amount // 总金额
        }
        if (!!form.saleOrderFeeDetailCode) {
          proxy.$api.OrderBusniess.UpdateSaleOrderFeeDetail(_form)
            .then((res: any) => {
              _sun()
            })
            .catch(() => {
              pup.loading = false
            });
        } else {
          proxy.$api.OrderBusniess.AddSaleOrderFeeDetail(_form)
            .then((res: any) => {
              _sun()
            })
            .catch(() => {
              pup.loading = false
            });
        }
        function _sun() {
          pup.state = false
          proxy.$message(`编辑成功`);
          getCostList()
        }
      }
    }
  ]
});
const amount = (form: any) => {
  const amount = proxy.$count(`${form.price || 0}*${form.number || 0}`)
  form.amount = amount
  return amount
}
const openPup = (row?: any) => {
  proxy.$openPup(pup, !!row ? 2 : 1)
  if (!!row) {
    pup.form = JSON.parse(JSON.stringify(row))
  }
}
//更新其他费用
const getCostList = () => {
  proxy.$api.OrderBusniess
    .GetMatchPageSaleOrderFeeDetails({
      pageIndex: 1,
      pageSize: 1000,
      queryDataBaseFiled: "",
      likeWords: "",
      onlySelf: 0,
      isShowDisabled: 0,
      orderByFiled: "",
      orderByType: 0,
      saleOrderCode: props.data.saleOrderCode,
      reconciliationStatus: 0,
    })
    .then((res: any) => {
      props.data.costList = res.list
    })
    .catch(() => {

    });
}
const totalAmountPrice = (row: any): number => {
  let price = 0
  const totalAmountPrice = proxy.$count(`${row.productQuantity || 0}*${row.unitPrice || 0}`, 3)
  const minimumAmount = row.orderProduct?.minimumAmount || 0
  switch (row.paymentMethod) {
    case 1://按照数量
      price = totalAmountPrice
      break;
    case 2://按最低价
      price = minimumAmount
      break;
    default://自动计算
      price = totalAmountPrice >= minimumAmount ? totalAmountPrice : minimumAmount
      break;
  }
  return price
}
//修改型号数量
const productionQuantity = (row: any) => {
  setTotalAmountPrice(row)
  row.dataQuantity = Math.floor(productQuantity(row) * 1.1)
}
//设置实际金额
const setTotalAmountPrice = (row: any) => {
  row.totalAmount = totalAmountPrice(row)
}
//计算优惠金额
const totalOffers = (row: any) => {
  return proxy.$count(`${row.totalAmount || 0}-${totalAmountPrice(row)}`, 3)
}
//计算产品数量
const productQuantity = (row: any): number => {
  const number = proxy.$arrTotal(row.orderProductSpecificationList, 'productionQuantity')
  row.productQuantity = number
  return number
}
//产品根据阶梯价获取最终价格
const productStepPrice = (row: any) => {
  let price = row.orderProduct.productPrice//产品单价
  const _setpRow = row.productSteppedPriceInfoList.findLast((el: any) => row.productQuantity >= el.productSteppedCount)
  if (_setpRow) {
    row.originalPrice = price
    price = _setpRow.productSteppedPrice
  } else {
    row.originalPrice = null
  }
  row.unitPrice = price
  return price
}
</script>
<style scoped lang="scss">
.producsBox {
  --m: 8px;

  .producsBox-head {
    display: flex;
    align-items: flex-start;

    >* {
      &:not(:last-child) {
        margin-right: var(--m);
      }
    }

    dl {
      display: flex;
      line-height: height 22px;

      dt {
        color: $info;
      }

      dd {
        flex: 1;
      }
    }

    .producsBox-main {
      flex: 1;
      overflow: hidden;
    }
  }
}
</style>